"""
This module provides a Flask application for querying movies by release time.
"""

from flask import Flask, request, jsonify
from peewee import MySQLDatabase, Model, CharField, FloatField, IntegerField

# 初始化 Flask 应用
app = Flask(__name__)

# 数据库配置，与实验三中的配置保持一致
db = MySQLDatabase(
    "1", host="localhost", port=3306, user="root", passwd="3218560376jJ"
)


class Movie(Model):
    """
    Represents a movie entity with detailed information.

    Attributes:
        title (CharField): The title of the movie.
        rating_num (FloatField): The rating of the movie.
        comment_num (IntegerField): The number of comments.
        directors (CharField): The director(s) of the movie.
        actors (CharField): The actor(s) of the movie.
        year (CharField): The release year of the movie.
        country (CharField): The country where the movie was produced.
        category (CharField): The category of the movie.
        pic (CharField): The URL of the movie poster.
    """

    title = CharField(max_length=200)
    rating_num = FloatField()
    comment_num = IntegerField()
    directors = CharField(max_length=200)
    actors = CharField(max_length=200)
    year = CharField(max_length=10)
    country = CharField(max_length=100)
    category = CharField(max_length=100)
    pic = CharField(max_length=200)

    class Meta:
        """Meta information for the Movie model."""
        database = db
        table_name = 'douban_movie'


@app.route('/movies_by_time', methods=['GET'])
def get_movies_by_time():
    """
    Queries movies by release time.

    Returns:
        JSON response containing the list of movie titles released in the specified year.
    """
    release_time = request.args.get('release_time')
    if not release_time:
        return jsonify({"error": "请提供上映时间"}), 400

    # 查询数据库中的电影
    movies_query = Movie.select().where(Movie.year == release_time)
    if not movies_query:
        return jsonify({"error": "未找到该年份的电影"}), 404

    result = [movie.title for movie in movies_query]
    return jsonify({"movies": result})


if __name__ == '__main__':
    app.run(debug=True)
